import { defineStore } from 'pinia'

export const useAuthStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: JSON.parse(localStorage.getItem('user')) || null,
    loggedIn: false, // 登录状态
  }),

  getters: {
    isAuthenticated: (state) => !!state.token
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    setUser(user) {
      this.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },

    clearToken() {
      this.token = null
      localStorage.removeItem('token')
    },

    clearUser() {
      this.user = null
      localStorage.removeItem('user')
    },

    login(token, user) {
      this.setToken(token)
      this.setUser(user)
      this.loggedIn = true;
    },

    logout() {
      this.clearToken()
      this.clearUser()
      this.loggedIn = false;
    },
    restore() {
      const token = localStorage.getItem('token');
      const user = localStorage.getItem('user');

      if (token) {
        this.token = token;
        this.loggedIn = true; // 设置登录状态
      }
      if (user) {
        this.user = JSON.parse(user);
      }
    },
  }
})
